package com.rtmart.image.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

public class FileTools {

    public static Boolean deleteFile(File file){
        try {
            if (file.exists() && file.isFile()){
                return  file.delete();
            }
            else {
                return false;
            }
        } catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

//    public static void deleteDir(File dir){
//        if (null == dir){
//            return ;
//        }
//
//        if (dir.exists() && dir.isDirectory()){
//            File[] fileList = dir.listFiles();
//            for (File tempFile : fileList){
//                deleteDir(tempFile);
//            }
//            dir.delete();
//        } else if (dir.exists() && dir.isFile()){
//            dir.delete();
//        }
//    }

    public static Boolean savaFile(MultipartFile multipartFile, File file){
        BufferedOutputStream out;
        try {
            out = new BufferedOutputStream(new FileOutputStream(file));
            out.write(multipartFile.getBytes());
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    //图片路径算法
    public static List<String> imageUrlList(File file) {
        List<String> imageUrlList = new ArrayList<>();
        if (file.exists() && file.isDirectory()) {
            File[] fileList = file.listFiles();
            for (File tempFile : fileList) {
                if (tempFile.exists() && tempFile.isFile()){
                    try {
                        String fileType = Files.probeContentType(tempFile.toPath());
                        if (fileType.equals("image/jpeg") || fileType.equals("image/gif") || fileType.equals("image/png") || fileType.equals("image/bmp")){
                            imageUrlList.add(tempFile.getName());
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return imageUrlList;
    }
}
